<?php

namespace App\Http\Controllers;

use App\Model\Cate;
use Illuminate\Http\Request;

class CateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $cates = Cate::all();
        return view("cate.index", compact('cates'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view("cate.create");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request,Cate $cate)
    {
        $this->validate($request,[
            'name'=>'required|min:1|max:6|unique:cates',
            'status'=>'required|in:0,1',
        ]);

        $cate->name = $request->name;
        $cate->status = $request -> status;
        $res = $cate->save();
        if ($res){
            return [
                'error' => 0,
                'info' => '添加成功',
            ];
        }
        return [
            'error'=>1,
            'info' => '添加失败,自己想想原因',
        ];

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Cate $cate)
    {
        return view('cate.edit',compact('cate'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Cate $cate)
    {
        //
        $this->validate($request,[
            'name'=>'required|min:1|max:6|unique:users,'.$cate->id,
            'status'=>'required|in:0,1',
        ]);

        $cate->name = $request->name;
        $cate->status = $request -> status;
        $res = $cate->save();
        if ($res){
            return [
                'error' => 0,
                'info' => '修改成功',
            ];
        }
        return [
            'error'=>1,
            'info' => '修改失败,自己想想原因',
        ];
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function checkStatus(Cate $cate)
    {
        if ($cate->status == 0){
            $cate->status = '1';
        }else{
            $cate->status = '0';
        }
        $cate->save();
    }
}
